package org.ccay.web.support.servlet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.Application;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.request.impl.RequestContextManager;
import org.ccay.web.support.internal.impl.RequestUtil;

/**
 * Servlet 分配器
 */
public class CcayServletDispatcher extends HttpServlet {
	public static final String PARAMS = "/params/";
	private ILogger log = CcayLoggerFactory.getLogger(CcayServletDispatcher.class);
	private static final long serialVersionUID = -2302064831234884941L;

 
	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		log.info("Init Spring Managed Servlets...");
		//增加上下文对象,避免初始化权限检查报错  
		if (RequestContextManager.getCurrent(true) == null) {
			RequestContext rc = new RequestContext();
			rc.setSkipSecurityCheck(true);
			rc.setApplication(Application.getCurrent());
			RequestContextManager.setCurrent(rc);
		}
		Map<String,Servlet> servlets = Ccay.getContext().getBeansOfType(Servlet.class);
		for(Servlet servlet: servlets.values()){
			servlet.init(servletConfig);
		}		
	}
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Servlet servletBean = getServlet(req);		 
		servletBean.service(req,resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Servlet servletBean = getServlet(req);
		servletBean.service(req,resp);
	}
	
	
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Servlet servletBean = getServlet(req);
		servletBean.service(req,resp);
	}
	
	
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Servlet servletBean = getServlet(req);
		servletBean.service(req,resp);
	}

	
	/** 
	 * 查找Bean
	 * @param req
	 * @param resp
	 * @return
	 * @throws FileNotFoundException 
	 */
	private Servlet getServlet(HttpServletRequest req) throws FileNotFoundException { 
		String uri = RequestUtil.getShortUri(req);
		
		if(uri.contains(PARAMS)){
			uri = uri.substring(0,uri.indexOf(PARAMS));
		}
		
		log.debug("Ready to dispatch with uri:{0}",uri);
		
		if(!Ccay.getContext().containsBean(uri)){
			throw new FileNotFoundException();
		}
		
		return Ccay.getContext().getBean(uri,Servlet.class);
	}
 
}
